package com.fmi.timedealer;

import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * Class, representing the screen for creation of a new action.
 * It is activated when user press on "Create Action" button from the main screen
 */
public class ActivityItemActivity extends Activity {
	
	public final static String ACTIVITY_TO_EDIT_KEY = "ActivityToEdit";
	public final static String SELECTED_CATEGORY = "SelectedCategory";
	public final static String RESULT_ACTIVITY_ITEM = "ResultActivityItem";
	
	private IDataManager dbManager = null;

	// indicate if the activity is called to create or edit activity item
	// if selectedCategory is null, than the case is "Edit Activity", if not - "Create Activity"
	private String selectedCategory;
	private ActivityItem activityToEdit;
	private ActivityItem resultActivityItem;
	
	/** Called when the activity is first created. */
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
       
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.create_action);
        
		dbManager = new SQLiteDataManager("MyDB", this);
		
		Bundle extras = getIntent().getExtras();
		activityToEdit = (ActivityItem) extras.getSerializable(ACTIVITY_TO_EDIT_KEY);
		selectedCategory = extras.getString(SELECTED_CATEGORY);
		
		// get components
		final Spinner categoriesSpinner = (Spinner) findViewById(R.id.spinner);
		final EditText activityNameText = (EditText) findViewById(R.id.add_name);
		final EditText activtyDescriptionText = (EditText) findViewById(R.id.add_description);
		Button createActionButton = (Button) findViewById(R.id.btnCreateAction);

		// initialize categories spinner
		@SuppressWarnings({ "rawtypes"})	
		ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, dbManager.getCategoriesNames());
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		categoriesSpinner.setAdapter(adapter);
        
        // if case is "Create Activity" - preselect and disable the category
		if(selectedCategory != null) {
			categoriesSpinner.setEnabled(false);
			categoriesSpinner.setSelection(adapter.getPosition(selectedCategory));
		} 
		// if case is "Edit Activity" - preselect all activity item properties
		else { 
			activityNameText.setText(activityToEdit.getName());
			activtyDescriptionText.setText(activityToEdit.getDescription());
			categoriesSpinner.setSelection(adapter.getPosition(activityToEdit.getCategory()));
		}
		
		// set button text according to the case - Edit/Create
		createActionButton.setText(selectedCategory == null ? "Edit Activity" : "Create Activity");
		createActionButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				String name = activityNameText.getText() != null ? activityNameText.getText().toString() : null;
				String description = activtyDescriptionText.getText() != null ? activtyDescriptionText.getText().toString() : null;
				String category = categoriesSpinner.getSelectedItem() != null ? categoriesSpinner.getSelectedItem().toString() : null;
				
				ActivityItem activityItemHandled = null;
				if(selectedCategory != null) {
					activityItemHandled = new ActivityItem(name, description, category);
				}
				else {
					activityToEdit.setName(name);
					activityToEdit.setDescription(description);
					activityToEdit.setCategory(category);
					activityItemHandled = activityToEdit;
				}
				String validationMessages = validateData(activityItemHandled);
				if(validationMessages != null && !validationMessages.equals("")) {
					
					Toast.makeText(getApplicationContext(), "Activity is not saved! \n" + validationMessages, Toast.LENGTH_SHORT).show();
					return;
				}
				
				boolean success = false;
				String performedAction = "";
				if(selectedCategory == null) {
					performedAction = "edited";
					activityToEdit.setName(activityItemHandled.getName());
					activityToEdit.setDescription(activityItemHandled.getDescription());
					activityToEdit.setCategory(activityItemHandled.getCategory());
					success = dbManager.updateActivityItem(activityToEdit);
					resultActivityItem = activityToEdit;
				}
				else {
					performedAction = "created";
					success = dbManager.recordActivityItem(activityItemHandled);
					resultActivityItem = activityItemHandled;
				}
				if(success) {
					Toast.makeText(getApplicationContext(), "Successfully " + performedAction + " activity '"
							+ activityItemHandled.getName() + "'", Toast.LENGTH_SHORT).show();
				}
				else {
					Toast.makeText(getApplicationContext(), "A technical problem occured, activity is not created", Toast.LENGTH_SHORT).show();
				}
							
				returnResult(RESULT_OK);
			}
		});
    }	

	protected String validateData(ActivityItem newAction) {
		
		StringBuilder messages = new StringBuilder();
		
		if(newAction.getName() == null || newAction.getName().equals("")) {
			messages.append("'Activity Name' is required \n");
		}
		if(newAction.getDescription() == null || newAction.getDescription().equals("")) {
			messages.append("'Description' is required \n");
		}
		if(newAction.getName() == null || newAction.getCategory().equals("")) {
			messages.append("'Category' is required \n");
		}
		
		return messages.toString();
	}

	private void returnResult(int resultCode) {

		if (resultCode == RESULT_OK) {
			getIntent().removeExtra(RESULT_ACTIVITY_ITEM);
			getIntent().putExtra(RESULT_ACTIVITY_ITEM, resultActivityItem);
		}
		this.setResult(resultCode, getIntent());
		this.finish();
	}
}
 